using System;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.IO;

namespace TBOCrypto
{
    public class AKSEnvelope
    {

        public static byte[] SignMsg(string message)
        {
            Encoding unicode = Encoding.Unicode;
            byte[] messageBytes = unicode.GetBytes(message);

            X509Certificate2 signerCert = CertsMan.GetMyCertificate();
            X509Certificate2 recipientCert = CertsMan.GetRecipientCertificate();

            ContentInfo contentInfo = new ContentInfo(messageBytes);
            SignedCms signedCms = new SignedCms(contentInfo);
            CmsSigner cmsSigner = new CmsSigner(signerCert);
            signedCms.ComputeSignature(cmsSigner);

            byte[] signedMsg = signedCms.Encode();

            contentInfo = new ContentInfo(signedMsg);
            EnvelopedCms envelopeCms = new EnvelopedCms(contentInfo);
            CmsRecipient cmsRecipient = new CmsRecipient(recipientCert);
            envelopeCms.Encrypt(cmsRecipient);

            byte[] output = envelopeCms.Encode();
            using (FileStream fs = new FileStream("C:\\envMessage", FileMode.Create))
            {
                fs.Write(output, 0, output.Length);
            }

            return output;
        }

        //public bool VerifyMessage()
        //{
        //    SignedCms signedCms = new SignedCms();

        //    signedCms.Decode(encodedSignedCms);

        //    signedCms.CheckSignature(true);
        //    return true;
        //}

        public static byte[] DecodeMessage()
        {
            byte[] messageBytes;
            using (FileStream fs = new FileStream("C:\\envMessage", FileMode.Open))
            {
                messageBytes = new byte[fs.Length];
                fs.Read(messageBytes, 0, (int)fs.Length);
            }

            EnvelopedCms envelopeCms = new EnvelopedCms();
            envelopeCms.Decode(messageBytes);
            envelopeCms.Decrypt(envelopeCms.RecipientInfos[0]);

            SignedCms signedCms = new SignedCms();
            signedCms.Decode(envelopeCms.Encode());
            signedCms.CheckSignature(true);

            return signedCms.ContentInfo.Content;
        }
    }
}
